import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import 'package:tencent_cloud_chat_demo/utils/authService.dart';
import 'package:tencent_cloud_chat_demo/utils/commonUtils.dart';
import 'package:tencent_cloud_chat_demo/utils/picture.dart';
import 'package:tencent_cloud_chat_demo/utils/request.dart';
import 'package:tencent_cloud_chat_demo/utils/toast.dart';

import 'package:tencent_cloud_chat_uikit/tencent_cloud_chat_uikit.dart';
import 'package:tencent_cloud_chat_uikit/ui/utils/screen_utils.dart';
import 'package:tencent_cloud_chat_uikit/ui/widgets/avatar.dart';
import 'package:tencent_cloud_chat_demo/src/provider/theme.dart';
import 'package:tencent_chat_i18n_tool/tencent_chat_i18n_tool.dart';

import 'package:flutter_easyloading/flutter_easyloading.dart';

import 'register_success.dart';

class RegisterSetting extends StatefulWidget {
  final String email;
  final String phone;
  final String password;
  final String captcha;

  const RegisterSetting({
    Key? key,
    required this.email,
    required this.phone,
    required this.password,
    required this.captcha,
  }) : super(key: key);

  @override
  State<StatefulWidget> createState() => RegisterSettingState();
}

class RegisterSettingState extends State<RegisterSetting> {
  String faceUrl = 'https://yunpengim.daboluo.pro/uploads/touxiang.jpg';
  late DateTime selectedDate;

  String userName = '';
  final TextEditingController userNameController = TextEditingController();
  String securityQ = '';
  final TextEditingController securityQController = TextEditingController();
  String securityA = '';
  final TextEditingController securityAController = TextEditingController();

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
    userNameController.dispose();
    securityQController.dispose();
    securityAController.dispose();
  }

  Future<void> showSelectAvatarPage(BuildContext context) async {
    final avatar = await uploadAvatar(isRegister: true);
    if (avatar != null) {
      setState(() {
        faceUrl = avatar;
      });
    }
  }

  Future<void> userRegister() async {
    final deviceId = await AuthService.getDeviceId();

    if (faceUrl.trim() == '') {
      ToastUtils.toast(TIM_t("请设置头像"));
      return;
    }

    if (userName.trim() == '') {
      ToastUtils.toast(TIM_t("请设置你的昵称"));
      return;
    }

    if (securityQ.trim() == '') {
      ToastUtils.toast(TIM_t("请设置安全问题"));
      return;
    }

    if (securityA.trim() == '') {
      ToastUtils.toast(TIM_t("请设置安全答案"));
      return;
    }

    if (deviceId == null) {
      ToastUtils.toast(TIM_t("获取设备ID失败"));
      return;
    }

    EasyLoading.show(status: '注册中...');
    try {
      appRequest(
        method: 'post',
        path: 'https://yunpengim.daboluo.pro/api/user/register',
        data: {
          'nickname': userName,
          'answer': securityA,
          'question': securityQ,
          'avatar': faceUrl,
          'email': widget.email,
          'mobile': widget.phone,
          'password': widget.password,
          'deviceId': deviceId,
          'captcha': widget.captcha,
        },
      ).then((res) async {
        debugPrint("注册结果: $res");
        if (res.data?['code'] == 1) {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => RegisterSuccess(
                account: res.data?['data']?['userinfo']?['account'] ?? '',
                securityQ: res.data?['data']?['userinfo']?['question'] ?? '',
                securityA: res.data?['data']?['userinfo']?['answer'] ?? '',
                password: res.data?['data']?['userinfo']?['password'] ?? '',
              ),
            ),
          );
        }
      });
    } catch (e) {
      ToastUtils.toast(TIM_t("网络故障，请稍后重试"));
    } finally {
      EasyLoading.dismiss();
    }
  }

  @override
  Widget build(BuildContext context) {
    final theme = Provider.of<DefaultThemeData>(context).theme;
    final isWideScreen =
        TUIKitScreenUtils.getFormFactor(context) == DeviceType.Desktop;
    return Scaffold(
      appBar: isWideScreen
          ? null
          : AppBar(
              iconTheme: const IconThemeData(
                color: Colors.white,
              ),
              shadowColor: theme.weakDividerColor,
              elevation: 1,
              title: Text(
                TIM_t("注册"),
                style: const TextStyle(color: Colors.white, fontSize: 17),
              ),
              flexibleSpace: Container(
                decoration: const BoxDecoration(
                  gradient: LinearGradient(
                    colors: [
                      Colors.black,
                      Colors.grey,
                    ],
                  ),
                ),
              ),
            ),
      body: Stack(
        children: [
          Container(
            padding: const EdgeInsets.all(20),
            color: isWideScreen
                ? theme.wideBackgroundColor
                : theme.wideBackgroundColor,
            child: Column(
              children: [
                GestureDetector(
                  child: TIMUIKitOperationItem(
                    isEmpty: false,
                    operationName: TIM_t("头像"),
                    operationRightWidget: SizedBox(
                      width: 48,
                      height: 48,
                      child: Avatar(faceUrl: faceUrl, showName: ""),
                    ),
                  ),
                  onTap: () => showSelectAvatarPage(context),
                ),
                SizedBox(height: CommonUtils.adaptHeight(34)),
                TextField(
                  controller: userNameController,
                  autofocus: false,
                  decoration: InputDecoration(
                    contentPadding:
                        EdgeInsets.only(left: CommonUtils.adaptWidth(14)),
                    hintText: TIM_t("请设置你的昵称"),
                    hintStyle:
                        TextStyle(fontSize: CommonUtils.adaptFontSize(24)),
                    suffixIcon: userName.isNotEmpty
                        ? IconButton(
                            icon: const Icon(Icons.clear, color: Colors.grey),
                            onPressed: () {
                              setState(() {
                                userName = '';
                                userNameController.clear();
                              });
                            },
                          )
                        : null,
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(8.0),
                      borderSide: const BorderSide(color: Colors.grey),
                    ),
                    focusedBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(8.0),
                      borderSide: const BorderSide(color: Colors.black),
                    ),
                  ),
                  keyboardType: TextInputType.text,
                  onChanged: (v) {
                    setState(() {
                      userName = v;
                    });
                  },
                ),
                SizedBox(height: CommonUtils.adaptHeight(34)),
                TextField(
                  controller: securityQController,
                  autofocus: false,
                  decoration: InputDecoration(
                    contentPadding:
                        EdgeInsets.only(left: CommonUtils.adaptWidth(14)),
                    hintText: TIM_t("请设置安全问题"),
                    hintStyle:
                        TextStyle(fontSize: CommonUtils.adaptFontSize(24)),
                    suffixIcon: securityQ.isNotEmpty
                        ? IconButton(
                            icon: const Icon(Icons.clear, color: Colors.grey),
                            onPressed: () {
                              setState(() {
                                securityQ = '';
                                securityQController.clear();
                              });
                            },
                          )
                        : null,
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(8.0),
                      borderSide: const BorderSide(color: Colors.grey),
                    ),
                    focusedBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(8.0),
                      borderSide: const BorderSide(color: Colors.black),
                    ),
                  ),
                  keyboardType: TextInputType.text,
                  onChanged: (v) {
                    setState(() {
                      securityQ = v;
                    });
                  },
                ),
                SizedBox(height: CommonUtils.adaptHeight(34)),
                TextField(
                  controller: securityAController,
                  autofocus: false,
                  decoration: InputDecoration(
                    contentPadding:
                        EdgeInsets.only(left: CommonUtils.adaptWidth(14)),
                    hintText: TIM_t("请设置安全答案"),
                    hintStyle:
                        TextStyle(fontSize: CommonUtils.adaptFontSize(24)),
                    suffixIcon: securityA.isNotEmpty
                        ? IconButton(
                            icon: const Icon(Icons.clear, color: Colors.grey),
                            onPressed: () {
                              setState(() {
                                securityA = '';
                                securityAController.clear();
                              });
                            },
                          )
                        : null,
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(8.0),
                      borderSide: const BorderSide(color: Colors.grey),
                    ),
                    focusedBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(8.0),
                      borderSide: const BorderSide(color: Colors.blue),
                    ),
                  ),
                  keyboardType: TextInputType.text,
                  onChanged: (v) {
                    setState(() {
                      securityA = v;
                    });
                  },
                ),
                Container(
                  margin: EdgeInsets.only(
                    top: CommonUtils.adaptHeight(46),
                  ),
                  child: Row(
                    children: [
                      Expanded(
                        child: ElevatedButton(
                          child: Text(TIM_t("完成注册"),
                              style: const TextStyle(color: Colors.white)),
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.black,
                          ),
                          onPressed: userRegister,
                        ),
                      )
                    ],
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
